package HTTPRecieveParser;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.StringTokenizer;
import java.io.*;
import java.sql.*;

import DatabaseManager.*;
import HTTPSendIntegrator.MmsMessageException;


public class SendReq {
	
	private String sendReqortReqMessage;
	
	public static final String MMS_MESSAGE_TYPE = "X-Mms-Message-Type:";
	public static final String MMS_TRANSACTION_ID = "X-Mms-Transaction-ID:";
	public static final String MMS_VERSION = "X-Mms-MMS-Version:";
	public static final String MMS_TO = "To:";
	public static final String MMS_CC = "CC:"; 
	public static final String MMS_BCC = "BCC:";
	public static final String MMS_FROM = "From:";
	public static final String MMS_CONTENT_TYPE = "Content-Type:";
	public static final String MMS_DATE = "Date:";
	public static final String MMS_SUBJECT = "Subject:";
	public static final String MMS_EXPIRY = "X-Mms-Expiry:";
	public static final String MMS_DELIVERY_TIME = "X-Mms-Delivery-Time:";
	public static final String MMS_DELIVERY_REPORT = "X-Mms-Delivery-Report:";
	public static final String MMS_READ_REPLY = "X-Mms-Read-Reply:";
	public static final String MMS_STORE = "X-Mms-Store:";
	
	public static final String MMS_RESPONSE_STATUS = "X-Mms-Response-Status";
	public static final String MMS_MESSAGE_ID = "Message-ID";
	
	private String mmsMessageType;
	private String mmsTransactionId;
	private String mmsVersion;
	private ArrayList<String> mmsTo;
	private ArrayList<String> mmsCc;
	private ArrayList<String> mmsBcc;
	private ArrayList<String> mmsPart;
	private String mmsFrom;
	private String mmsContentType;	
	private String mmsDate;
	private String mmsSubject;
	private String mmsExpiryTime;
	private Boolean mmsExpiryTimeAbsolute;
	private String mmsDeliveryTime;
	private Boolean mmsDeliveryTimeAbsolute;	
	private Boolean mmsDeliveryReport;
	private Boolean mmsReadReply;
	private Boolean mmsStore;
	private String mmsMessageId;
	private String mmsMessageSize;
	
	private String mimeID;
	private String mimeType;
	private String mimeLocation;
	
	public String getMessageSize(){
		return mmsMessageSize;
	}
	
	public String getContentLocation(){
		return mmsMessageId;
	}
	
	public String getMessageType(){
		return mmsMessageType;
	}
	
	public String getTransactionId(){
		return mmsTransactionId;
	}
	
	public String getMessageId(){
		return mmsMessageId;
	}

	public List<String> getTo(){
		return mmsTo;
	}

	public List<String> getCc(){
		return mmsCc;
	}
	
	public List<String> getBcc(){
		return mmsBcc;
	}
	
	public String getFrom(){
		return mmsFrom;
	}

	public String getContentType(){
		return mmsContentType;
	}
	
	public String getDate(){
		return mmsDate;
	}
	
	public String getSubject(){
		return mmsSubject;
	}
	
	public String getExpiryTime(){
		return mmsExpiryTime;
	}
	
	public Boolean getExpiryTimeAbsolute(){
		return mmsExpiryTimeAbsolute;
	}
	
	public String getDeliveryTime(){
		return mmsDeliveryTime;
	}

	public Boolean getDeliveryTimeAbsolute(){
		return mmsDeliveryTimeAbsolute;
	}
	
	public Boolean getDeliveryReport(){
		return mmsDeliveryReport;
	}
	
	public Boolean getReadReply(){
		return mmsReadReply;
	}

	public Boolean getStore(){
		return mmsStore;
	}
	
	public SendReq(String sendReqortReqMessage){
		this.sendReqortReqMessage = sendReqortReqMessage;
		this.mmsStore = true;
		this.mmsTo = new ArrayList<String>();
		this.mmsCc = new ArrayList<String>();
		this.mmsBcc = new ArrayList<String>();
		this.mmsPart = new ArrayList<String>();
	}
	
	public void decodeMessage() throws MmsMessageException,  SQLException, IOException{
		MMBoxManager mmBoxManager = new MMBoxManager();
		TempMSGBox tempMsgBox = new TempMSGBox();
		
		mmBoxManager.ConnectDB();
		tempMsgBox.ConnectDB();
		/**
		 * MeessageId Creation
		 */
		Random mID;
		int ran;
		do{
			mID = new Random(System.currentTimeMillis());
			ran = mID.nextInt();
			if(ran<0)
				ran *= -1;
			mmsMessageId = "MID" + ran;
		}while(mmBoxManager.isExistMsgId(mmsMessageId) &&
				tempMsgBox.isExistMsgId(mmsMessageId));
		
		try{
			String[] result = sendReqortReqMessage.split("\n");
			String boundary = "";

			for(int i=0; i<result.length; i++)
			{
				if(result[i].startsWith(MMS_MESSAGE_TYPE))
					mmsMessageType=(result[i].substring((result[i].indexOf(':'))+2));
				
				else if(result[i].startsWith(MMS_TRANSACTION_ID))
					mmsTransactionId=result[i].substring((result[i].indexOf(':'))+2);

				
				else if(result[i].startsWith(MMS_MESSAGE_ID))
					mmsVersion=result[i].substring((result[i].indexOf(':'))+2);
				
				else if(result[i].startsWith(MMS_TO))
					mmsTo.add(result[i].substring((result[i].indexOf(':'))+2));

				else if(result[i].startsWith(MMS_CC))
					mmsCc.add(result[i].substring((result[i].indexOf(':'))+2));
								
				else if(result[i].startsWith(MMS_BCC))
					mmsBcc.add(result[i].substring((result[i].indexOf(':'))+2));

				
				else if(result[i].startsWith(MMS_FROM))
					mmsFrom=result[i].substring((result[i].indexOf(':'))+2);

				else if(result[i].startsWith(MMS_CONTENT_TYPE))
					mmsContentType=result[i].substring((result[i].indexOf(':'))+2);

				
				else if(result[i].startsWith(MMS_DATE))
					mmsDate=result[i].substring((result[i].indexOf(':'))+2);

				
				else if(result[i].startsWith(MMS_SUBJECT))
					mmsSubject=result[i].substring((result[i].indexOf(':'))+2);


				else if(result[i].startsWith(MMS_EXPIRY))
					mmsExpiryTime=result[i].substring((result[i].indexOf(':'))+2);

				else if(result[i].startsWith(MMS_DELIVERY_TIME))
					mmsDeliveryTime=result[i].substring((result[i].indexOf(':'))+2);

				else if(result[i].startsWith(MMS_DELIVERY_REPORT))
				{
					if(result[i].substring((result[i].indexOf(':'))+2)=="YES")
						mmsDeliveryReport=true;
						mmsDeliveryReport=false;
				}
				
				else if(result[i].startsWith(MMS_READ_REPLY))
				{
					if(result[i].substring((result[i].indexOf(':'))+2)=="YES")
						mmsDeliveryReport=true;
					else
						mmsDeliveryReport=false;
				}
				
				else if(result[i].startsWith(MMS_STORE))
				{
					if(result[i].substring((result[i].indexOf(':'))+2)=="YES")
						mmsDeliveryReport=true;
					else
						mmsDeliveryReport=false;
				}
				
				else if(result[i].startsWith("boundary="))
				{
					boundary = "--"+result[i].substring((result[i].indexOf('='))+1);
				}
			}

			String[] multipart = sendReqortReqMessage.split(boundary);
			//System.out.println(multipart[1]);
			for(int i=0; i<multipart.length; i++){
				if(i!=0)
				{
						//mmsPart.add(multipart[i]);
					
						String mimeBody = multipart[i];
						String [] mimeLine = mimeBody.split("\r\n");

						mimeID=mimeLine[0].substring((mimeLine[0].indexOf(':'))+2);
						mimeType=mimeLine[1].substring((mimeLine[1].indexOf(':'))+2);
						mimeLocation=mimeLine[2].substring((mimeLine[2].indexOf(':'))+2);
						
						String mimeBodyPart = "";
						if(mimeLine.length > 3)
						{
							for(int j=4; j<mimeLine.length-1; j++)
							mimeBody += mimeLine[j];
						}
						File file = new File("./MMBox/"+mmsMessageId+"/"+mimeLocation);
						FileOutputStream out = new FileOutputStream(file);
						out.write(mimeBodyPart.getBytes());
						out.close();
				}
			}
			
			mmBoxManager.CloseConnectionDB();
			tempMsgBox.CloseConnectionDB();

		}catch (ArrayIndexOutOfBoundsException e){
			System.out.println("Malformed response message");
		}
	}
	
	public void StoreMMS() throws SQLException{
		MMBoxManager mmBoxManager = new MMBoxManager();
		TempMSGBox tempMsgBox = new TempMSGBox();
		System.out.println("to : "+ mmsTo.size() + " cc : " + mmsCc.size() + " bcc : " + mmsBcc.size());
		String[] mm = new String[14];
		String[] to = mmsTo.toArray(new String[mmsTo.size()]);
		String[] cc = mmsCc.toArray(new String[mmsCc.size()]);
		String[] bcc = mmsBcc.toArray(new String[mmsBcc.size()]);
		
		mm[0] = mmsMessageId;
		mm[1] = mmsSubject;
		mm[2] = "/MMbox/"+mmsMessageId; // ContentLocation
		mm[3] = mmsDate;
		mm[4] = mmsExpiryTime;
		mm[5] = mmsDeliveryTime;
		mm[6] = mmsFrom;
		////////////////////////////////////////////////////////////////////////
		//to = sendReqMsg.getTo();
		///////////////////////////////////////////////////////////////////////
		mm[8] = mmsDeliveryReport.toString();
		mm[9] = null;
		mm[10] = null;
		mm[11] = null;
		mm[12] = null;
		mm[13] = null;
		
		if(mmsStore)
		{
			mmBoxManager.ConnectDB();
			mmBoxManager.StoreMessage(mm, to, cc, bcc);
			mmBoxManager.CloseConnectionDB();			
		}else	
		{
			tempMsgBox.ConnectDB();
			tempMsgBox.StoreMessage(mm, to, cc, bcc);
			tempMsgBox.CloseConnectionDB();
		}
	}
}
